#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QMessageBox>
#include <QTime>
#include <QSound>
#include <QMediaPlayer>
#include <cfg/inifile.h>
#include "config.h"
#include "QSettings"
#include "QTextCodec"
#include "QSound"
MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow),m_pClient(nullptr)
{
    ui->setupUi(this);
    ui->textBrowser_message->document()->setMaximumBlockCount(5000);
    connect(ui->lineEdit_Publish,ui->lineEdit_Publish->returnPressed,this,&MainWindow::on_Btn_Publish_clicked);
    char data[1024] = {0};
    //read user name from inifile.
    if (0 != read_profile_string(USER_NAME_SECTION,USER_NAME_KEY,data,sizeof(data),"user name",CFG_INI_FILE_NAME))
    {
        write_profile_string(USER_NAME_SECTION,USER_NAME_KEY,"user name",CFG_INI_FILE_NAME);
    }
    QString str = "";
    str += data;
    ui->lineEdit_userName->setText(str);
    //read server ip from inifile.
    memset(data,0,sizeof(data));
    str = "";

    if( 0 !=read_profile_string(SERVER_SECTION,SERVER_IP_KEY,data,sizeof(data),"47.101.62.66",CFG_INI_FILE_NAME))
    {
        write_profile_string(SERVER_SECTION,SERVER_IP_KEY,"47.101.62.66",CFG_INI_FILE_NAME);
    }
    str += data;
    ui->lineEdit_IP->setText(str);
    memset(data,0,sizeof(data));
    str = "";
    if (0 != read_profile_string(SERVER_SECTION,SERVER_PORT_KEY,data,sizeof(data),"10086",CFG_INI_FILE_NAME))
    {
        write_profile_string(SERVER_SECTION,SERVER_PORT_KEY,"10086",CFG_INI_FILE_NAME);
    }
    str += data;
    ui->lineEdit_Port->setText(str);
    m_connectTime = new QTimer();
    connect(m_connectTime,&QTimer::timeout,this,[&]()
    {
        QMessageBox::information(nullptr,"提示","连接超时!",QMessageBox::Ok);
        on_Btn_Connect_clicked();
    });
}

MainWindow::~MainWindow()
{
    delete ui;
}




void MainWindow::onConnected()
{
     if (m_connectTime->isActive())
     {
         m_connectTime->stop();
     }
     QMessageBox::information(nullptr,"提示","连接成功!",QMessageBox::Ok);
     ui->Btn_Connect->setText("断开连接");
     ui->Btn_Connect->setEnabled(true);
     ui->lineEdit_IP->setEnabled(false);
     ui->lineEdit_Port->setEnabled(false);
     ui->lineEdit_userName->setEnabled(false);     
     //after connected,save user name to cfg file.
     write_profile_string(USER_NAME_SECTION,USER_NAME_KEY,ui->lineEdit_userName->text().toLatin1().data(),CFG_INI_FILE_NAME);
     write_profile_string(SERVER_SECTION,SERVER_IP_KEY,ui->lineEdit_IP->text().toLatin1().data(),CFG_INI_FILE_NAME);
     write_profile_string(SERVER_SECTION,SERVER_PORT_KEY,ui->lineEdit_Port->text().toLatin1().data(),CFG_INI_FILE_NAME);
}

void MainWindow::onSubscribed(const QString &topic)
{
     QMessageBox::information(nullptr,"提示","订阅成功!订阅内容:"+topic,QMessageBox::Ok);
}


void MainWindow::onUnSubscribed(const QString &topic)
{
    QMessageBox::information(nullptr,"提示","取消订阅成功!订阅内容:"+topic,QMessageBox::Ok);
    ui->lineEdit_topic->setEnabled(true);
}

void MainWindow::onPublished(const QMQTT::Message& message)
{
    ui->lineEdit_Publish->clear();
}


void MainWindow::onReceived(const QMQTT::Message &message)
{
    QString str = message.payload().toStdString().data();

    if (!str.contains(ui->lineEdit_userName->text()))
    {
        QSound::play("shake.wav");
    }
    ui->textBrowser_message->append(message.payload().toStdString().data());

}

void MainWindow::on_Btn_Connect_clicked()
{
    static bool isClicked = false;
    if (ui->lineEdit_IP->text() == "")
    {
        QMessageBox::warning(nullptr,"错误","内容不能为空",QMessageBox::Ok);
        return;
    }
    if (ui->lineEdit_Port->text() == "")
    {
        QMessageBox::warning(nullptr,"错误","内容不能为空",QMessageBox::Ok);
        return;
    }
    if (ui->lineEdit_userName->text() == "")
    {
        QMessageBox::warning(nullptr,"错误","内容不能为空",QMessageBox::Ok);
        return;
    }
    QHostAddress addr(ui->lineEdit_IP->text());
    quint16 port = ui->lineEdit_Port->text().toShort();
    if (ui->lineEdit_userName->text().length() > 20)
    {
        QMessageBox::warning(nullptr,"错误","用户名长度为1-20",QMessageBox::Ok);
        return;
    }

    if (!isClicked)
    {        
        isClicked = true;
        if (m_pClient == nullptr)
        {
            m_pClient = new QMQTT::Client(addr,port);
            m_pClient->setClientId(ui->lineEdit_userName->text());
            connect(m_pClient, &QMQTT::Client::connected, this, &MainWindow::onConnected);
            connect(m_pClient, &QMQTT::Client::subscribed, this, &MainWindow::onSubscribed);
            connect(m_pClient, &QMQTT::Client::unsubscribed,this,&MainWindow::onUnSubscribed);
            connect(m_pClient, &QMQTT::Client::published, this, &MainWindow::onPublished);
            connect(m_pClient, &QMQTT::Client::received,  this, &MainWindow::onReceived);
            m_pClient->setAutoReconnect(true);
            m_pClient->connectToHost();
            ui->Btn_Connect->setText("正在连接...");
            ui->Btn_Connect->setEnabled(false);
            m_connectTime->start(5000);
        }

    }
    else
    {
        if (ui->Btn_Subscib->text() == "取消订阅")
        {
            QMessageBox::warning(nullptr,"提示","请先取消订阅后再断开连接!",QMessageBox::Ok);
            return;
        }
        isClicked = false;
        if (m_pClient != nullptr)
        {
            m_pClient->disconnect();
            ui->Btn_Connect->setText("连接");
            ui->lineEdit_IP->setEnabled(true);
            ui->lineEdit_Port->setEnabled(true);
            ui->lineEdit_userName->setEnabled(true);
            ui->Btn_Connect->setEnabled(true);
            delete m_pClient;
            m_pClient = nullptr;
        }
    }
}





void MainWindow::on_Btn_Subscib_clicked()
{
    static bool isClicked = false;

    if ((m_pClient != nullptr) && (m_pClient->isConnectedToHost()))
    {
        if (!isClicked)
        {
            isClicked = true;
            m_pClient->subscribe(ui->lineEdit_topic->text(),QOS);
            ui->Btn_Subscib->setText("取消订阅");
            ui->lineEdit_topic->setEnabled(false);
        }
        else
        {
            isClicked = false;
            m_pClient->unsubscribe(ui->lineEdit_topic->text());
            ui->Btn_Subscib->setText("订阅主题");
        }
    }
    else
    {
        QMessageBox::information(nullptr,"提示","未连接,请先连接到服务器",QMessageBox::Ok);
        return;
    }
}

void MainWindow::on_Btn_Publish_clicked()
{
    if ((m_pClient != nullptr) && (m_pClient->isConnectedToHost()))
    {
        QMQTT::Message msg;
        msg.setQos(QOS);
        msg.setTopic(ui->lineEdit_topic->text());
        QString str = QTime::currentTime().toString("hh:mm:ss ") +  ui->lineEdit_userName->text() + ":\r\n";
        str += ui->lineEdit_Publish->text();
        msg.setPayload(str.toUtf8());
        m_pClient->publish(msg);
        ui->Btn_Subscib->setText("取消订阅");
        ui->lineEdit_topic->setEnabled(false);

    }
    else
    {
        QMessageBox::information(nullptr,"提示","未连接,请先连接到服务器",QMessageBox::Ok);
        return;
    }
}

void MainWindow::on_Btn_ClearText_clicked()
{
    ui->textBrowser_message->clear();
}
